package org.jeecgframework.web.service.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyContactsServiceI;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.ZyCinemaEntity;
import org.jeecgframework.web.system.pojo.base.ZyContactsEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("zyContactsService")
@Transactional
public class ZyContactsServiceImpl extends CommonServiceImpl implements ZyContactsServiceI {
    
    private static  final Logger logger  = Logger.getLogger(ZyContactsServiceImpl.class);

    @Autowired
    private SystemService systemService;

    @Autowired
	private ZyCommonService zyCommonService;

 	public <T> void delete(T entity) {
 		super.delete(entity);
 		//执行删除操作配置的sql增强
		this.doDelSql((ZyContactsEntity)entity);
 	}
 	
 	public <T> Serializable save(T entity) {
 		Serializable t = super.save(entity);
 		//执行新增操作配置的sql增强
// 		this.doAddSql((ZyContactsEntity)entity);
 		return t;
 	}
 	
 	public <T> void saveOrUpdate(T entity) {
 		super.saveOrUpdate(entity);
 		//执行更新操作配置的sql增强
// 		this.doUpdateSql((ZyContactsEntity)entity);
 	}
 	
 	/**
	 * 默认按钮-sql增强-新增操作
	 * @return
	 */
 	public boolean doAddSql(ZyContactsEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-更新操作
	 * @return
	 */
 	public boolean doUpdateSql(ZyContactsEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-删除操作
	 * @return
	 */
 	public boolean doDelSql(ZyContactsEntity t){
	 	return true;
 	}
 	
 	/**
	 * 替换sql中的变量
	 * @param sql
	 * @return
	 */
 	public String replaceVal(String sql,ZyContactsEntity t){
 		sql  = sql.replace("#{id}",String.valueOf(t.getId()));
 		sql  = sql.replace("#{base_id}",String.valueOf(t.getTsBaseUser().getId()));
 		sql  = sql.replace("#{name}",String.valueOf(t.getName()));
 		sql  = sql.replace("#{cellphone1}",String.valueOf(t.getCellphone1()));
 		sql  = sql.replace("#{cellphone2}",String.valueOf(t.getCellphone2()));
 		sql  = sql.replace("#{telephone}",String.valueOf(t.getTelephone()));
 		sql  = sql.replace("#{gender}",String.valueOf(t.getGender()));
 		sql  = sql.replace("#{state}",String.valueOf(t.getState()));
 		sql  = sql.replace("#{email}",String.valueOf(t.getEmail()));
 		sql  = sql.replace("#{position}",String.valueOf(t.getPosition()));
 		sql  = sql.replace("#{source}",String.valueOf(t.getSource()));
 		sql  = sql.replace("#{con_business}",String.valueOf(t.getConBusiness()));
 		sql  = sql.replace("#{type}",String.valueOf(t.getType()));
 		sql  = sql.replace("#{create_name}",String.valueOf(t.getCreateName()));
 		sql  = sql.replace("#{create_by}",String.valueOf(t.getCreateBy()));
 		sql  = sql.replace("#{create_date}",String.valueOf(t.getCreateDate()));
 		sql  = sql.replace("#{update_name}",String.valueOf(t.getUpdateName()));
 		sql  = sql.replace("#{update_by}",String.valueOf(t.getUpdateBy()));
 		sql  = sql.replace("#{update_date}",String.valueOf(t.getUpdateDate()));
 		sql  = sql.replace("#{UUID}",UUID.randomUUID().toString());
 		return sql;
 	}

	@Override
	public String checkTpIpHeaderUnique(String belongOrg,String id) {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT COUNT(1) AS total,name ");
		sql.append(" FROM zy_contacts ");
		sql.append(" WHERE ");
		sql.append(" belong_org = '"+belongOrg+"'");
		sql.append(" AND position = '"+StaticValue.DIC_CONTACT_POSITION_TP_SERVER_BUSINESSR+"'");
		sql.append(" AND con_business LIKE '%"+StaticValue.DIC_BUS_SCOPE_INSPECTION+"%' ");
		sql.append(" AND state = '"+StaticValue.DIC_ENGINEER_STATE_ONJOB+"' ");
		sql.append(" AND is_delete = 0 ");
		if(id != null){
			sql.append(" AND id != '"+id+"'");
		}
		List<Map<String,Object>> mapList = super.findForJdbc(sql.toString());
		
		String name = null;
		if(null != mapList && mapList.size() > 0 && null != mapList.get(0).get("name")){
			name = mapList.get(0).get("name").toString();
		}
		return name;
	}

	@Override
	public boolean checkCtUnique(String name, String cellphone1, String id) {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT COUNT(1) AS total FROM zy_contacts ");
		sql.append(" WHERE ");
		sql.append(" name = '"+name+"'");
		sql.append(" AND cellphone1 = '"+cellphone1+"'");
		if(id != null){
			sql.append(" AND id != '"+id+"'");
		}
		int total = zyCommonService.getCountBySql(sql.toString());
		if(total > 0){
			return false;
		}
		return true;
	}

    public ZyContactsEntity findContactByUserName(String userName) {
        if(oConvertUtils.isNotEmpty(userName)){
            List<ZyContactsEntity> contacts = findHql("from ZyContactsEntity where tsBaseUser.userName=?",userName);
            if(!CollectionUtils.isEmpty(contacts)){
                return contacts.get(0);
            }
        }
        return new ZyContactsEntity();
    }


    public List<ZyContactsEntity> findContactsListByCinema(String cinemaId) {
        logger.info(cinemaId);
        List<ZyContactsEntity> contacts = new ArrayList<ZyContactsEntity>();
        if(StringUtil.isEmpty(cinemaId)){
            return contacts;
        }
        if(get(ZyCinemaEntity.class,cinemaId) == null){
            return contacts;
        }
        String hql = "from ZyContactsEntity where belongCinema.id=? and state='onJob' and isDelete=0 and type='cinema_contact'";
        logger.info(hql);
        return findHql(hql,cinemaId);
    }

    @Override
    public List<ZyContactsEntity> findContactsInSameCinema(String contactId) {
        List<ZyContactsEntity> contacts = new ArrayList<ZyContactsEntity>();
        if(StringUtil.isEmpty(contactId)){
            return contacts;
        }
        ZyContactsEntity me = get(ZyContactsEntity.class,contactId);
        if(StringUtil.isNotEmpty(me) && me.getBelongCinema() != null){
            return findContactsListByCinema(me.getBelongCinema().getId());
        }
        return contacts;
    }

    @Override
    public List<ZyContactsVo> genViewObject(List<ZyContactsEntity> contacts) {
        List<ZyContactsVo> contactsVos = new ArrayList<ZyContactsVo>();
        if (contacts == null) {
            return contactsVos;
        }
        for (ZyContactsEntity ct : contacts) {
            contactsVos.add(new ZyContactsVo(ct));
        }
        return contactsVos;
    }

    @Override
    public ZyContactsEntity addContactByUser(TSUser user) {
        ZyContactsEntity contacts = new ZyContactsEntity();
        contacts.setType(StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT);
        contacts.setName(user.getRealName());
        contacts.setCellphone1(user.getMobilePhone());
        contacts.setSource("微信注册");
        contacts.setIsDelete("0");
        contacts.setTsBaseUser(user);
        systemService.save(contacts);
        return contacts;
    }

    @Override
    public List<ZyContactsEntity> getAddressByPhone(String phone) {
        return findHql("from ZyContactsEntity cd where cd.cellphone1=? or cd.cellphone2=? order by updateDate desc,createDate desc",phone,phone);
    }


    public class ZyContactsVo{
        private String name;
        private String email;
        private String id;
        private String cellphone1;
        private String state;
        private String stateText;
        private String position;
        private String positionText;
        private String level;

        ZyContactsVo(ZyContactsEntity ct){
            this.setName(ct.getName());
            this.setCellphone1(ct.getCellphone1());
            this.setId(ct.getId());
            this.setState(ct.getState());
            this.setPosition(ct.getPosition());
            this.setPositionText(systemService.getTypeByCode(StaticValue.DIC_CINEMA_DEPART,ct.getPosition()));
            this.setStateText(systemService.getTypeByCode("engineer_state",ct.getState()));
            this.setEmail(ct.getEmail());
            this.setLevel("无");
            if(ct.getTsBaseUser() != null){
                if(ct.getTsBaseUser().ifGoldMedal()){
//                    this.setLevel("金牌");
                    this.setLevel("钻石");
                }else{
                    this.setLevel("银牌");
                }
            }
        }


        public String getLevel() {
            return level;
        }

        public void setLevel(String level) {
            this.level = level;
        }

        public String getName() {
            return name;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getCellphone1() {
            return cellphone1;
        }

        public void setCellphone1(String cellphone1) {
            this.cellphone1 = cellphone1;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }

        public String getStateText() {
            return stateText;
        }

        public void setStateText(String stateText) {
            this.stateText = stateText;
        }

        public String getPosition() {
            return position;
        }

        public void setPosition(String position) {
            this.position = position;
        }

        public String getPositionText() {
            return positionText;
        }

        public void setPositionText(String positionText) {
            this.positionText = positionText;
        }
    }
}